/**
 * Created by Lwang on 2017/3/5.
 * 所有文章
 *
 */

"use strict";

import {square, ajax} from './resize.js';
import {way} from "./common.js";
import $ from "jquery";
import * as async from "./async.js";
require("./layer.js");
import {weChat} from "./weChat.js";
require("./jquery.form.min.js");
require("./ajaxfileupload.js");
const Handlebars = require("./handlebars");

square(document, window);
$(function () {
    let pageData = [],
        textInput = $("#j-word"),
        teacherHeadImg = "",
        teachimg = "",
        ispause = false,
        couseInfo, teacherInfo, isBlod = 0,
        timeoutQuickClick
        ;


    $("#j-content ul").eq(0).html("");

    Handlebars.registerHelper("isShow", function (v1, v2, options) {
        if (v1 == v2) {
            return "display:block";
        } else {
            return "display:none";
        }
    });

    Handlebars.registerHelper("textTohtml", function (str) {
        return new Handlebars.SafeString(str);
    });

    //  获取课程和教师信息
    async.waterfall([(callback) => {
        layer.open({
            type: 2,
            content: "正在加载"
        });
        way._login(() => {
            callback();
        });
    }, (callback) => {
        $.ajax({
            url: ajax.course(),
            xhrFields: {
                withCredentials: true
            },
            success: (res) => {
                couseInfo = res;
                callback(null);
            }
        });
    }, (res) => {
        $.ajax({
            url: ajax.teacherInfo,
            xhrFields: {
                withCredentials: true
            },
            success: (res) => {
                teacherInfo = res;
                teachimg = res.headImg;
                teacherHeadImg = res.headImg;
                layer.closeAll();
            }
        });
    }], (ex) => {
        layer.closeAll();
        layer.open("网络异常, 请重试!", {
            icon: 1,
            skin: "layer-ext-moon"
        });
    });


    //录音注册
    weChat.record("", function (serverid, time) {
        recordUpload(serverid, time);
    });
    //播放录音与暂停
    function toPlay(_self) {
        var timeout;
        var audio = $(_self).find(".j-audio")[0],
            self = _self,
            duration = audio.duration,
            trueduration = new Number($(self).find(".videonum").find("a").html()),
            currentTime = audio.currentTime;

        if (currentTime == 0) {
            audio.play();
            $(self).find(".playicon").find("img").attr("src","images/play.gif");
            timeout = setTimeout(function () {
                $(self).find(".playicon").find("img").attr("src","images/audio.png");
            },trueduration * 1000);
        } else if (currentTime == duration) {
            audio.load();
            audio.play();
            $(self).find(".playicon").find("img").attr("src","images/play.gif");
            timeout = setTimeout(function () {
                $(self).find(".playicon").find("img").attr("src","images/audio.png");
            },trueduration * 1000);
        } else {
            if (ispause) {
                trueduration = trueduration - currentTime;
                timeout = setTimeout(function () {
                    $(self).find(".playicon").find("img").attr("src","images/audio.png");
                },trueduration * 1000);
                audio.play();
                $(self).find(".playicon").find("img").attr("src","images/play.gif");
            } else {
                clearTimeout(timeout);
                audio.pause();
                $(self).find(".playicon").find("img").attr("src","images/audio.png");
            }
            ispause = !ispause;
        }

    }

    //录音上传与回写

    function recordUpload(media_id, time) {
        layer.open({
            type: 2,
            content: "正在加载"
        });
        async.waterfall([() => {
            const data = {
                "content": "http://m.studypointshare.com/mp3/" + media_id + ".mp3",
                "contentType": "VIDEO",
                "courseId": couseInfo.id,
                "id": couseInfo.id,
                duration: time,
                "sort": 0,
                "status": "ENABLED"
            };
            $.ajax({
                url: ajax.addContent,
                type: "POST",
                headers: {
                    "Content-Type": "application/json;charset=UTF-8"
                },
                data: JSON.stringify(data),
                xhrFields: {
                    withCredentials: true
                },
                success: (res) => {
                    layer.closeAll();
                    pageData.push(res);
                    var myTemplate = Handlebars.compile($("#listTemplate").html());
                    $("#j-content ul").eq(0).html(myTemplate(pageData));
                    $(".ae-img").find("img").attr("src", teacherHeadImg);
                    //初始化录音
                    $(".aec-audio").click(function () {
                        toPlay(this);
                    });

                    //  点击图片预览
                    var picArr = [];
                    $.each(pageData, (index, obj) => {
                        if (obj.contentType == "IMAGE") {
                            picArr.push(obj.content);
                        }
                    });
                    $(".aec-picture").click(function () {
                        var self = this;
                        weChat.chooseImg($(self).find("img").attr("src"), picArr);
                    });

                    //图片大小处理
                    $.each($("#courseDetail li").find(".aec-picture").find("img"), function (index, obj) {
                        way.picSizeCtrl(obj, ".aec-picture");
                    });

                }
            });
        }], () => {
            layer.closeAll();
            layer.open({
                type: 1,
                content: "网络异常, 请重试!"
            });
        });
    }


    //  上传与回写
    function upload(file) {
        layer.open({
            type: 2,
            content: "正在加载"
        });

        $("#head-form").ajaxSubmit({
            "type": "post",
            "dataType": "json",
            "url": ajax.upload + "?space=uquiz_image",
            "success": function (resopnse) {
                let id = resopnse.id,
                    data = {
                        "content": ajax.file(id),
                        "contentType": "IMAGE",
                        "courseId": couseInfo.id,
                        "id": id,
                        duration: 0,
                        "sort": 0,
                        "status": "ENABLED"
                    };
                if (id) {
                    $.ajax({
                        url: ajax.addContent,
                        type: "POST",
                        headers: {
                            "Content-Type": "application/json;charset=UTF-8"
                        },
                        data: JSON.stringify(data),
                        xhrFields: {
                            withCredentials: true
                        },
                        success: (res) => {
                            layer.closeAll();
                            pageData.push(res);
                            var myTemplate = Handlebars.compile($("#listTemplate").html());
                            $("#j-content ul").eq(0).html(myTemplate(pageData));
                            $(".ae-img").find("img").attr("src", teacherHeadImg);
                            //初始化录音
                            $(".aec-audio").click(function () {
                                toPlay(this);
                            });
                            //  点击图片预览
                            var picArr = [];
                            $.each(pageData, (index, obj) => {
                                if (obj.contentType == "IMAGE") {
                                    picArr.push(obj.content);
                                }
                            });
                            $(".aec-picture").click(function () {
                                var self = this;
                                weChat.chooseImg($(self).find("img").attr("src"), picArr);
                            });

                            //图片大小处理
                            $.each($("#courseDetail li").find(".aec-picture").find("img"), function (index, obj) {
                                console.log(obj)
                                way.picSizeCtrl(obj, ".aec-picture");
                            });
                        }
                    });
                }
            }
        });

    }

    //  添加内容与回写
    function addContent(content) {
        layer.open({
            type: 2,
            content: "正在加载"
        });
        async.waterfall([() => {
            const data = {
                "content": content,
                "contentType": "TEXT",
                "courseId": couseInfo.id,
                "id": 0,
                duration: 0,
                "sort": 0,
                "status": "ENABLED"
            };
            $.ajax({
                url: ajax.addContent,
                type: "POST",
                headers: {
                    "Content-Type": "application/json;charset=UTF-8"
                },
                data: JSON.stringify(data),
                xhrFields: {
                    withCredentials: true
                },
                success: (res) => {
                    layer.closeAll();
                    pageData.push(res);
                    var myTemplate = Handlebars.compile($("#listTemplate").html());
                    $("#j-content ul").eq(0).html(myTemplate(pageData));
                    $(".ae-img").find("img").attr("src", teacherHeadImg);
                    //初始化录音
                    $(".aec-audio").click(function () {
                        toPlay(this);
                    });

                    //  点击图片预览
                    var picArr = [];
                    $.each(pageData, (index, obj) => {
                        if (obj.contentType == "IMAGE") {
                            picArr.push(obj.content);
                        }
                    });
                    $(".aec-picture").click(function () {
                        var self = this;
                        weChat.chooseImg($(self).find("img").attr("src"), picArr);
                    });


                    //图片大小处理
                    $.each($("#courseDetail li").find(".aec-picture").find("img"), function (index, obj) {
                        way.picSizeCtrl(obj, ".aec-picture");
                    });
                }
            });
        }], () => {
            layer.closeAll();
            layer.open({
                type: 1,
                content: "网络异常, 请重试!"
            });
        });
    }

    //  加粗
    $("div.be-bold").on("touchend", () => {
        clearTimeout(timeoutQuickClick);
        timeoutQuickClick = setTimeout(function () {
            isBlod++;
            if (isBlod % 2 != 0) {
                $(".beb-true").css("display", "block");
                $(".beb-false").css("display", "none");
            } else {
                $(".beb-true").css("display", "none");
                $(".beb-false").css("display", "block");
            }
            document.execCommand("bold", false, null);
        }, 300);
    });

    //  添加内容
    $(".be-send").on("click", () => {
        // let content = editor.body.innerHTML.replace(/\<b\>/gim, "<b style='font-weight: bold;'>");
        let content = $("#j-word").html();
        if (!content) {
            layer.open({
                type: 1,
                content: "请先输入内容!"
            });
            return;
        }
        addContent(content);
        $("#j-word").html("");
    });

    //  文件上传
    $("input.be-upload").on("change", (e) => {
        const file = $("input.be-upload").get(0).files[0];
        if (file.size < 5000000) {
            upload(file);
        } else {
            layer.open({
                type: 1,
                content: "选择的图片大小不得超过5兆!",
                time: 1
            });
        }
        e.preventDefault();
    });

    //  完成
    $("#j-completeBtn").on("click", (e) => {
        const title = $("input.atew-input").val().trim();
        if (!title) {
            layer.open({
                type: 1,
                content: "请先输入标题!"
            });
            return;
        }
        if (!pageData.length) {
            layer.open({
                type: 1,
                content: "请先添加内容!"
            });
            return;
        }

        pageData = pageData.map((item, index) => {
            item.courseId = couseInfo.id;
            item.id = couseInfo.id;
            item.sort = 0;
            item.status = "ENABLED";
            return item;
        });

        const data = {
            title,
            contents: pageData,
            courseId: couseInfo.id,
            teacherId: teacherInfo.id,
            id: couseInfo.id,
            sort: 0,
            status: "ENABLED"
        };

        $.ajax({
            url: ajax.couseEdit,
            type: "POST",
            headers: {
                "Content-Type": "application/json;charset=UTF-8"
            },
            data: JSON.stringify(data),
            xhrFields: {
                withCredentials: true
            },
            success: (res) => {
                layer.closeAll();
                layer.open({
                    type: 1,
                    content: "发布成功!即将返回首页!"
                });
                setTimeout(() => {
                    location.href = "/newest.html";
                }, 2000);
            }
        });
    });

    //  相关事件
    $(".ber-record").click(function () {
        $(this).css("display", "none");
        $(".ber-key").css("display", "block");
        $("#j-word").css("display", "none");
        $(".no-press").css("display", "block");
        $(".has-press").css("display", "none");
        $(".be-img").css("display", "block");
        $(".be-send").css("display", "none");
    });
    $(".ber-key").click(function () {
        $(this).css("display", "none");
        $("#j-word").css("display", "block");
        $(".ber-record").css("display", "block");
        $(".no-press").css("display", "none");
        $(".has-press").css("display", "none");
        $(".be-img").css("display", "none");
        $(".be-send").css("display", "block");
    })
    //监听focus
    $("#j-word").focus(function () {
        setTimeout(function () {
            var scrollH = $(document).scrollTop(),
                nowScrollH = scrollH + 100;
            $(document).scrollTop(nowScrollH);
        },400);
    })
});


